<template>
  <div class="city-detail">
    <!-- 返回按钮 -->
    <div class="back-section">
      <button class="back-btn" @click="goBack">
        <span class="back-icon">←</span>
        返回城市列表
      </button>
    </div>

    <!-- 城市详情内容 -->
    <div class="detail-content" v-if="city">
      <!-- 顶部信息栏 -->
      <section class="city-header">
        <div class="city-hero">
          <img :src="city.image" :alt="city.name" class="hero-image" />
          <div class="hero-overlay">
            <h1 class="city-title">{{ city.name }}</h1>
            <div class="city-rating-large">⭐ {{ city.rating }}</div>
          </div>
        </div>
      </section>

      <!-- 城市基本信息 -->
      <section class="city-basic-info">
        <div class="info-grid">
          <div class="info-item">
            <span class="info-label">最佳旅行时间</span>
            <span class="info-value">{{ city.bestSeason }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">推荐天数</span>
            <span class="info-value">{{ city.recommendedDays }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">浏览量</span>
            <span class="info-value">{{ formatNumber(city.views) }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">推荐数</span>
            <span class="info-value">{{ city.recommendations }}</span>
          </div>
        </div>
      </section>

      <!-- 城市描述 -->
      <section class="city-description-section">
        <h2>城市介绍</h2>
        <p class="city-full-description">{{ city.description }}</p>
      </section>

      <!-- 城市标签 -->
      <section class="city-tags-section">
        <h2>特色标签</h2>
        <div class="tags-container">
          <span
            v-for="tag in city.tags"
            :key="tag"
            :class="['tag', 'tag-large', getTagClass(tag)]"
          >
            {{ tag }}
          </span>
        </div>
      </section>

      <!-- 热门景点 -->
      <section class="attractions-section">
        <h2>热门景点</h2>
        <div class="attractions-grid">
          <div
            v-for="attraction in city.attractions"
            :key="attraction"
            class="attraction-card"
          >
            <div class="attraction-icon">🏞️</div>
            <span class="attraction-name">{{ attraction }}</span>
          </div>
        </div>
      </section>

      <!-- 操作按钮 -->
      <section class="action-buttons">
        <button class="btn-primary btn-large" @click="planTrip">
          🗺️ 规划行程
        </button>
        <button
          class="btn-recommend btn-large"
          @click="handleRecommend"
          :disabled="isRecommending"
        >
          ⭐ {{ isRecommending ? '推荐中...' : '推荐城市' }}
        </button>
        <button class="btn-secondary btn-large" @click="saveToWishlist">
          💖 {{ inWishlist ? '已在心愿单（点击移除）' : '加入心愿单' }}
        </button>
      </section>
    </div>
  </div>
</template>

<script>
import { getCityById, recommendCity } from '../../api/city'
import {
  getWishlist,
  addToWishlist,
  removeFromWishlist
} from '../../api/wishlist'
import { authUtils } from '../../utils/auth'
export default {
  name: 'CityDetail',
  data() {
    return {
      city: null,
      wishlistIds: [],
      isRecommending: false
    }
  },
  mounted() {
    this.loadCityData()
    this.loadWishlist()
  },
  computed: {
    inWishlist() {
      const id = this.city?.id
      return id ? this.wishlistIds.includes(id) : false
    }
  },
  methods: {
    async loadCityData() {
      try {
        const cityId = Number(this.$route.params.id)
        const data = await getCityById(cityId)
        if (!data || !data.id) {
          this.$router.push('/cities')
          return
        }
        // 保障数组字段可用
        data.tags = Array.isArray(data.tags) ? data.tags : []
        data.attractions = Array.isArray(data.attractions)
          ? data.attractions
          : []
        this.city = data
      } catch (e) {
        console.error('获取城市详情失败:', e)
        this.$router.push('/cities')
      }
    },
    loadWishlist() {
      const fallback = () => {
        try {
          const raw = localStorage.getItem('cityWishlist')
          const arr = JSON.parse(raw || '[]')
          this.wishlistIds = Array.isArray(arr) ? arr : []
        } catch (e) {
          this.wishlistIds = []
        }
      }
      if (authUtils.isLoggedIn()) {
        getWishlist()
          .then((ids) => {
            this.wishlistIds = Array.isArray(ids) ? ids : []
          })
          .catch((err) => {
            console.error('获取心愿单失败:', err)
            fallback()
          })
      } else {
        fallback()
      }
    },
    goBack() {
      this.$router.back()
    },
    getTagClass(tag) {
      const tagMap = {
        美食: 'food',
        火锅: 'food',
        文化: 'culture',
        历史: 'culture',
        古迹: 'culture',
        古城: 'culture',
        自然: 'nature',
        湖泊: 'nature',
        雪山: 'nature',
        海岛: 'nature',
        休闲: 'leisure',
        浪漫: 'romance',
        夜景: 'night',
        魔幻: 'magic',
        熊猫: 'panda'
      }
      return tagMap[tag] || ''
    },
    formatNumber(num) {
      if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万'
      }
      return num.toString()
    },
    planTrip() {
      alert(`开始规划 ${this.city.name} 的行程！`)
      // 在实际应用中，这里会跳转到行程规划页面
    },
    async handleRecommend() {
      if (this.isRecommending) return

      this.isRecommending = true
      try {
        const result = await recommendCity(this.city.id)
        if (result.success) {
          this.$message?.success?.('推荐成功！')
          // 更新推荐数
          this.city.recommendations =
            result.data.recommendations || this.city.recommendations + 1
        } else {
          this.$message?.error?.(result.message || '推荐失败')
        }
      } catch (error) {
        console.error('推荐失败:', error)
        this.$message?.error?.('推荐失败，请稍后再试')
      } finally {
        this.isRecommending = false
      }
    },
    async saveToWishlist() {
      const id = this.city?.id
      if (!id) return
      if (authUtils.isLoggedIn()) {
        try {
          if (this.inWishlist) {
            await removeFromWishlist(id)
            this.$message?.success?.(`${this.city.name} 已从心愿单移除`)
            this.wishlistIds = this.wishlistIds.filter((x) => x !== id)
          } else {
            await addToWishlist(id)
            this.$message?.success?.(`${this.city.name} 已加入心愿单`)
            this.wishlistIds = [...this.wishlistIds, id]
          }
        } catch (e) {
          console.error('更新心愿单失败:', e)
          this.$message?.error?.('更新心愿单失败，请稍后再试')
        }
      } else {
        const set = new Set(this.wishlistIds)
        if (set.has(id)) {
          set.delete(id)
          this.$message?.success?.(`${this.city.name} 已从心愿单移除`)
        } else {
          set.add(id)
          this.$message?.success?.(`${this.city.name} 已加入心愿单`)
        }
        this.wishlistIds = Array.from(set)
        localStorage.setItem('cityWishlist', JSON.stringify(this.wishlistIds))
      }
    }
  },
  watch: {
    '$route.params.id': {
      handler() {
        this.loadCityData()
      },
      immediate: true
    }
  }
}
</script>

<style scoped>
.city-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

/* 返回按钮 */
.back-section {
  margin-bottom: 20px;
}

.back-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background: white;
  border: 1px solid #ddd;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  color: #666;
}

.back-btn:hover {
  border-color: #ff7e5f;
  color: #ff7e5f;
}

.back-icon {
  font-size: 16px;
}

/* 城市头部 */
.city-hero {
  position: relative;
  height: 400px;
  border-radius: 20px;
  overflow: hidden;
  margin-bottom: 30px;
}

.hero-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.hero-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  color: white;
  padding: 40px;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.city-title {
  font-size: 48px;
  font-weight: bold;
  margin: 0;
}

.city-rating-large {
  font-size: 24px;
  font-weight: bold;
}

/* 基本信息网格 */
.city-basic-info {
  margin-bottom: 40px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  background: #f8f9fa;
  padding: 30px;
  border-radius: 15px;
}

.info-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.info-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.info-value {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

/* 城市描述 */
.city-description-section {
  margin-bottom: 40px;
}

.city-description-section h2 {
  font-size: 28px;
  color: #333;
  margin-bottom: 20px;
}

.city-full-description {
  font-size: 16px;
  line-height: 1.8;
  color: #666;
  text-align: justify;
}

/* 标签区域 */
.city-tags-section {
  margin-bottom: 40px;
}

.city-tags-section h2 {
  font-size: 28px;
  color: #333;
  margin-bottom: 20px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.tag-large {
  padding: 8px 16px;
  font-size: 14px;
  border-radius: 20px;
}

/* 景点区域 */
.attractions-section {
  margin-bottom: 40px;
}

.attractions-section h2 {
  font-size: 28px;
  color: #333;
  margin-bottom: 20px;
}

.attractions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.attraction-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 15px;
  background: white;
  border: 1px solid #eaeaea;
  border-radius: 10px;
  transition: all 0.3s;
}

.attraction-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.attraction-icon {
  font-size: 20px;
}

.attraction-name {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 20px;
  justify-content: center;
  margin-top: 50px;
}

.btn-large {
  padding: 15px 30px;
  font-size: 16px;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
  min-width: 180px;
}

.btn-primary {
  background: #ff7e5f;
  color: white;
}

.btn-primary:hover {
  background: #ff6b4a;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(255, 126, 95, 0.3);
}

.btn-recommend {
  background: linear-gradient(135deg, #ffd700, #ffa500);
  color: white;
  font-weight: 600;
}

.btn-recommend:hover:not(:disabled) {
  background: linear-gradient(135deg, #ffa500, #ff8c00);
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(255, 165, 0, 0.4);
}

.btn-recommend:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.btn-secondary {
  background: white;
  color: #333;
  border: 1px solid #ddd;
}

.btn-secondary:hover {
  background: #f5f5f5;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

/* 标签样式（复用） */
.tag {
  background: #f0f7ff;
  color: #4a90e2;
}

.tag.food {
  background: #fff0f0;
  color: #ff7e5f;
}

.tag.culture {
  background: #f0fff4;
  color: #4caf50;
}

.tag.nature {
  background: #f0f8ff;
  color: #2196f3;
}

.tag.leisure {
  background: #fff8e1;
  color: #ff9800;
}

.tag.romance {
  background: #fce4ec;
  color: #e91e63;
}

.tag.night {
  background: #212121;
  color: #bb86fc;
}

.tag.magic {
  background: #7b1fa2;
  color: white;
}

.tag.panda {
  background: #000;
  color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .city-detail {
    padding: 15px;
  }

  .city-hero {
    height: 300px;
  }

  .hero-overlay {
    padding: 20px;
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .city-title {
    font-size: 36px;
  }

  .info-grid {
    grid-template-columns: repeat(2, 1fr);
    padding: 20px;
  }

  .action-buttons {
    flex-direction: column;
    align-items: center;
  }

  .btn-large {
    width: 100%;
    max-width: 300px;
  }
}

@media (max-width: 480px) {
  .city-title {
    font-size: 28px;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }

  .attractions-grid {
    grid-template-columns: 1fr;
  }
}
</style>
